var express = require('express');
var router = express.Router();
var { person_model } = require("../utils/model")
var { aesEncrypt } = require("../utils")

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

router.post("/register", function (req, res) {
  var body = req.body
  console.log(body);
  person_model.findOne({
    username: body.username
  }).then(result => {
    if (result) {
      res.send(`<script>alert('当前用户已经被注册,请重新提交注册');location.href='/register' </script>`)
    } else {
      // 插入数据
      body.time = new Date()
      person_model.insertMany({ ...body })
        .then(data => {
          console.log(data)
          res.send(`<script>alert('注册成功,立即前往登录');location.href='/login?username=${aesEncrypt(body.username)}' </script>`)
        })
        .catch(err => {
          res.send("服务器异常-500")
        })
    }
  }).catch(err => {
    res.send("服务器异常--500")
  })
})

router.post("/login", (req, res) => {
  var body = req.body
  // 查询  
  person_model.findOne({
    username: body.username
  }).then(result => {
    if (result) {
      console.log(req.session)
      if (result.pass == body.pass) {
        req.session.username = result.username;
        req.session.nickname = result.nickname
        req.session.phone = result.phone
        res.redirect("/")   // 登录成功  redirect 重定向到主页 
      } else {
        res.send(`<script>alert('密码不正确,请确认数据再登录');location.href="/login"; </script>`)
      }
    } else {
      res.send(`<script>alert('用户不存在,请确认数据再登录');location.href="/login"; </script>`)
    }
  })
    .catch(err => {
      res.send("服务器异常-500")
    })
})

module.exports = router;
